﻿package com.studiocode.aspeaker;

import java.util.Locale;
import java.util.concurrent.locks.ReentrantLock;


import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.media.*;

public class TTS implements OnInitListener
{
 
	public final String TAGDEBUG = "aSpeaker";
	
	private TextToSpeech tts;
	static final int TTS_CHECK_CODE = 0;
	private ReentrantLock waitForInitLock = new ReentrantLock(); 
	private String Text = "";
	//Solo per debug
	private boolean CanSpeak = false;
	
	Context myContext;
	
	public TTS(Context cont, String SpeakText, boolean canSpeak)
	{
		myContext = cont;
		tts = new TextToSpeech(cont,this);
		Locale loc = Locale.getDefault();
		tts.setLanguage(loc);
        waitForInitLock.lock();
        Text = SpeakText;
        CanSpeak = canSpeak;
	}
 
	@Override
	public void finalize()
	{
		if (tts != null)
		{
			tts.shutdown();
		}
	}
	
	@Override
	public void onInit(int initStatus)
	{
		if (initStatus == TextToSpeech.SUCCESS)
		{
			//Zittisco un attimo l'audio finche parla..
			//int ringMode = 0;
			final AudioManager am = (AudioManager) myContext.getSystemService(Context.AUDIO_SERVICE);
			try
			{
				if (am.isBluetoothScoOn())
				{
					//Tratto da http://android.voxisland.com/code_examples/How_to_enable_and_disable_the_silent_mode.rhtml
					Log.v(TAGDEBUG, "Redirezione audio al bluetooth");
					am.startBluetoothSco();
					am.setBluetoothScoOn(true);
				}
        	}
        	catch (Exception ex)
        	{
        		Log.v(TAGDEBUG, "TTS.onInit: " + ex.getMessage().toString());
        	}
			if (CanSpeak)
			{
				tts.speak(Text, TextToSpeech.QUEUE_FLUSH, null);
			}
			else
				Log.v(TAGDEBUG, "Ho parlato sottovoce '" + Text + "'");
				
			try
			{
				if (am.isBluetoothScoOn())
				{
					Log.v(TAGDEBUG, "Ripristino audio dal bluetooth");
					am.stopBluetoothSco();
					am.setBluetoothScoOn(false);
				}
			}
        	catch (Exception ex)
        	{
        		Log.v(TAGDEBUG, "TTS.onInit: " + ex.getMessage().toString());
        	}
		   	if (am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
		   	{
		   		am.adjustStreamVolume(AudioManager.STREAM_RING, 
		   			AudioManager.ADJUST_RAISE, AudioManager.FLAG_ALLOW_RINGER_MODES);
		   	}
		}
		else
			Log.v(TAGDEBUG, "TTS non inizializzato: " + String.valueOf(initStatus));
	}
}

